package ar.com.android.restoapp.adapters;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import ar.com.android.restoapp.forms.R;
import ar.com.android.restoapp.entities.Food;

public class AutoCompleteFoodAcapter extends ArrayAdapter<Food> implements Filterable {

	Activity activity;
	public List<Food> foods;
	private FoodFilter filter;
	List<Food> origFoods;
	
	public AutoCompleteFoodAcapter(Activity activity, int textViewResourceId, List<Food> foods)
	{
		super(activity, textViewResourceId, foods);
		this.activity = activity;
		this.foods = foods;
		filter = new FoodFilter();
	}
	
	@Override
	public int getCount() {
		if(foods != null)
			return foods.size();
		else
			return 0;
	}

	@Override
	public Food getItem(int position) {
		return foods.get(position);
	}

	@Override
	public long getItemId(int position) {
		return foods.get(position).getIdFood();
	}
	
	private class FoodView
	{
		TextView tvFood;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		FoodView fv;
		LayoutInflater inflater =  activity.getLayoutInflater();
		
		if(convertView == null)
		{
			convertView = inflater.inflate(R.layout.tv_food, null);
			fv = new FoodView();
			fv.tvFood = (TextView) convertView.findViewById(R.id.tvFood);
			
			convertView.setTag(fv);
		}
		else
			fv = (FoodView) convertView.getTag();
		
		fv.tvFood.setText(foods.get(position).toString());
		
		return convertView;
	}

	@Override
	public Filter getFilter() {
		return filter;
	}
	
	private class FoodFilter extends Filter
	{

		@Override
		protected FilterResults performFiltering(CharSequence constraint) {
			FilterResults oReturn = new FilterResults();
			List<Food> results = new ArrayList<Food>();
			if(origFoods == null)
				origFoods = foods;
			
			 if (constraint != null)
			 {
				 if (origFoods != null && origFoods.size() > 0) {                     
					 for (Food food : origFoods) {                            
						 if (food.getDescription().toUpperCase().contains(constraint.toString().toUpperCase()))   
							 results.add(food);
					 }
				 }
				 oReturn.values = results;
			 }
			return oReturn;
		}

		@SuppressWarnings("unchecked")
		@Override
		protected void publishResults(CharSequence constraint, FilterResults results) {
			foods = (List<Food>) results.values;
			notifyDataSetChanged();
		}
		
	}

}
